import { WeApp } from '../../../common/common';
import { config } from '../../../etc/config';
import * as __ from '../../../assets/plugins/underscore.js';
import httpClient from '../../../common/http-client';
import wxService from '../../../common/wxService';
import tools from '../../../common/tools';
import { ShopCart } from '../../../model/order';
import { Goods } from '../../../model/goods';
import * as wux from '../../../assets/components/wux';
import * as WxParse from '../../../assets/plugins/wxParse/wxParse.js';
import { IUser } from '../../../model/user';
import utils from '../../../utils/utils'
import { UserAuth } from '../../../common/auth';

const app: WeApp = getApp() as WeApp;

interface GoodsDetailPageData {
    attrsDialogHidden?: boolean,
    current: number,
    goods?: Goods,
    winHeight: number,
    currentDetailTab: number,
    shopCart?: {
        count?: number
    },
    userInfo?: IUser,
    btnEnable: boolean,
    count: number,
    isNow?: boolean,
    video?: Array<{ file_path?: string, file_name?: string }>
}


interface GoodsDetailPage extends IPage {
}

class GoodsDetailPage {
    data: GoodsDetailPageData = {
        current: 0,
        winHeight: 0,
        currentDetailTab: 0,
        attrsDialogHidden: false,
        btnEnable: true,
        count: 1
    }

    async getDetail(id) {
        const that = this;
        const res = await httpClient.get<Goods>(tools.buildUrl(config.goods.details, { id: id }))
        wx.hideLoading();
        if (!res.succeed) {
            wxService.showToast(res.msg);
            setTimeout(function () {
                wxService.navigateBack();
            }, 1000);
            return;
        }
        this.setData({
            goods: res.value
        })
        WxParse.wxParse("article", 'html', res.value.details, this, 0);
        this.setData({
            total: res.value.imgs.length
        })
    }


    async onLoad(option) {
        wxService.showLoading();
        const sysInfo: wx.GetSystemInfoResult = wx.getSystemInfoSync();
        const user = await app.getUserInfo();
        this.setData({
            'winHeight': sysInfo.windowHeight,
            'winWidth': sysInfo.windowWidth,
            'shopCart': { 'count': user.shopCar }
        });
        await this.getDetail(option.id);
    }

    detailBindChange(e) {
        this.setData(
            {
                currentDetailTab: e.detail.current
            })
    }

    menuSwichNav(e) {
        const target = e.currentTarget.dataset;
        if (this.data.currentDetailTab === target.current) {
            return false;
        }
        this.setData({
            currentDetailTab: target.current
        });
    }

    toggleDialog(e) {
        this.setData({
            'attrsDialogHidden': !this.data.attrsDialogHidden
        })
    }


    toCart(e) {
        wxService.switchTab('/pages/cart/list/index');
    }

    selectGoodsAttrs() {
        this.setData({
            'attrsDialogHidden': !this.data.attrsDialogHidden,
            'isNow': false
        })
    }

    decrease(e) {
        this.setCount(this.data.count + -1)
    }

    increase(e) {
        this.setCount(this.data.count + 1)
    }

    bindCountChange(e) {
        this.setCount(Math.abs(e.detail.value));
    }

    setCount(count: number) {
        count = count < 1 ? 1 : count;
        this.setData({
            'count': count
        });
    }

    goodsImgTap(e) {
        const target = e.currentTarget.dataset;
        wx.previewImage({
            current: this.data.goods.imgs[target.index],
            urls: this.data.goods.imgs
        })
    }

    toBuy(e) {
        this.setData({
            'attrsDialogHidden': !this.data.attrsDialogHidden,
            'isNow': true
        })
    }


    async addCart(e) {
        if (this.data.count == 0) {
            utils.showToastErr(`最少购买1${this.data.goods.unit || '件'}`);
            return;
        }
        if (!UserAuth.checkIsBuy()) {
            return;
        }
        let saveData = {
            'attrsDialogHidden': !this.data.attrsDialogHidden
        };
        if (!this.data.isNow) {
            wxService.showLoading("");
            const res = await httpClient.post(config.shopCart.shopcar_add,
                {
                    'goodsId': this.data.goods.id,
                    'count': this.data.count
                }
            );
            if (res.succeed) {
                wxService.showToast('已加入购物车');
                app.addCurUserShopCar(this.data.count);
                saveData['shopCart.count'] = this.data.shopCart.count + this.data.count;
            } else {
                utils.showToastErr(res.msg);
            }
        } else {
            if (!UserAuth.checkIsBuy()) {
                return;
            }
            const goods = this.data.goods;
            let goodsList = [{
                count: this.data.count,
                goodsId: goods.id,
                goodsName: goods.name,
                unit: goods.unit,
                img: goods.faceImg,
                unitPrice: goods.unitPrice
            }];
            wx.setStorageSync('confirmOrder', goodsList)
            wxService.redirectTo('/pages/order/confirm/index')
        }
        this.setData(saveData);
    }

    detailsMoblieImgEvent(e) {
        const target = e.currentTarget.dataset;
        wx.previewImage({
            current: this.data.goods.detailsMoblie[target.index],
            urls: this.data.goods.detailsMoblie
        })
    }

    videoEvent(e) {
        const index = e.currentTarget.dataset.index;
        const video = this.data.goods.video[index];
        wx.setStorageSync('video', {
            name: video.file_name,
            url: video.file_path
        });
        wxService.navigateTo('../video/index')
    }
}

Page(new GoodsDetailPage());
